package SMSGUI;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.*;
import javax.swing.text.html.*;

import jxl.write.WriteException;

public class trainStuff {
	final static int interval = 1000;
	static int i2;
	static JLabel label;
	static JProgressBar pb;
	static Timer timer;
	static JButton button;
	static JButton backButton;
	final JFrame frame = new JFrame("Training");
	
	public trainStuff(final HashMap<Integer, String[]> tweets) {
		
		button = new JButton("Start");
		backButton = new JButton("Terug");
		backButton.setVisible(false);
		button.addActionListener(new ButtonListener());
		backButton.addActionListener(new ButtonListener());
		final int howMuch = 60;// 2*tweets.keySet().size();
		pb = new JProgressBar(0, howMuch);
		pb.setValue(0);
		pb.setStringPainted(true);

		label = new JLabel("Klik start...");

		JPanel panel = new JPanel();
		panel.add(button);
		panel.add(backButton);
		panel.add(pb);

		JPanel panel1 = new JPanel();
		panel1.setLayout(new BorderLayout());
		panel1.add(panel, BorderLayout.NORTH);
		panel1.add(label, BorderLayout.CENTER);
		panel1.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
		frame.setContentPane(panel1);
		frame.pack();
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create a timer.
		timer = new Timer(interval, new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				System.out.println(howMuch + " " + i2);

				System.out.println("hoi");
				try {
					int kfold = 10;
					HashMap<Integer, HashMap<String, String>[]> sets = new HashMap<Integer, HashMap<String, String>[]>();
					HashMap<Integer, HashMap<String, Float>[]> wordCounters = new HashMap<Integer, HashMap<String, Float>[]>();
					HashMap<Integer, Integer> bestWordCounter = new HashMap<Integer, Integer>();
					for (int i = 1; i <= kfold; i++) {
						updatePb(1);
						// create sets: {trainset, validationset}
						HashMap<String, String>[] trainVilisetsK;

						trainVilisetsK = trainDataNeutralNonNeutral.createSets(
								tweets, i, kfold);

						sets.put(i, trainVilisetsK);
						// create counts: {zero, nonzero, all}
						HashMap<String, Float>[] wordCountsK = trainDataNeutralNonNeutral
								.createWordCounts(trainVilisetsK[0]);
						wordCounters.put(i, wordCountsK);
					}
					for (int i = 1; i <= kfold; i++) {
						updatePb(1);
						// {testset, validationset}
						HashMap<String, String>[] setsK = sets.get(i);
						// {zero, nonzero, all}
						HashMap<String, Float>[] wordCountersk = wordCounters
								.get(i);
						// {zero, nonzero}
						float[] sentimentChance = trainDataNeutralNonNeutral
								.getSentimentChance(setsK[0]);
						// classified: {zero, nonzero, validationZero,
						// validationNonZero};
						HashMap<String, String[]>[] classifications = trainDataNeutralNonNeutral
								.naiveBayes(setsK, sentimentChance,
										wordCountersk);

						HashMap<String, String>[] wrongsTrain = trainDataNeutralNonNeutral
								.getWrongs(classifications[0],
										classifications[1]);
						HashMap<String, String>[] wrongsValidation = trainDataNeutralNonNeutral
								.getWrongs(classifications[2],
										classifications[3]);

						int bestWrongs = wrongsValidation[0].size()
								+ wrongsValidation[1].size();

						int failUpdates = 0;
						int bestfound = 0;
						HashMap<String, String>[] stringarray = trainDataNeutralNonNeutral
								.floattostringarray(wordCountersk);
						writeExcel.write("bestWordCounterZero" + i + bestfound
								+ ".xls", stringarray[0]);
						writeExcel.write("bestWordCounterNonZero" + i
								+ bestfound + ".xls", stringarray[1]);
						writeExcel.write("bestWordCounterAll" + i + bestfound
								+ ".xls", stringarray[2]);
						updatePb(1);
						while (failUpdates < 3) {
							wordCountersk = trainDataNeutralNonNeutral
									.updateCounters(wrongsTrain, wordCountersk);
							classifications = trainDataNeutralNonNeutral
									.naiveBayes(setsK, sentimentChance,
											wordCountersk);
							wrongsTrain = trainDataNeutralNonNeutral.getWrongs(
									classifications[0], classifications[1]);
							wrongsValidation = trainDataNeutralNonNeutral
									.getWrongs(classifications[2],
											classifications[3]);
							/*
							 * System.out .println(
							 * "||||||||||||||||||TRAINSET||||||||||||||||||||||||"
							 * ); System.out.println("\t\t" + "NoSentiment\t" +
							 * "Sentiment"); System.out.println("classified:\t"
							 * + classifications[0].size() + "\t\t" +
							 * classifications[1].size());
							 * System.out.println("wrong:\t\t" +
							 * wrongsTrain[0].size() + "\t\t"+
							 * wrongsTrain[1].size()); System.out.println(
							 * "||||||||||||||||||||TestSet||||||||||||||||||||"
							 * ); System.out.println("\t\t" + "NoSentiment\t" +
							 * "Sentiment"); System.out.println("classified:\t"
							 * + classifications[2].size() + "\t\t" +
							 * classifications[3].size());
							 * System.out.println("wrong:\t\t" +
							 * wrongsValidation[0].size() + "\t\t"+
							 * wrongsValidation[1].size()); System.out.println(
							 * "||||||||||||||||||||||||||||||||||||||||||||||||"
							 * );
							 */
							int totalWrongs = wrongsValidation[0].size()
									+ wrongsValidation[1].size();
							if (totalWrongs < bestWrongs) {
								bestfound++;
								stringarray = trainDataNeutralNonNeutral
										.floattostringarray(wordCountersk);
								writeExcel.write("bestWordCounterZero" + i
										+ bestfound + ".xls", stringarray[0]);
								writeExcel.write("bestWordCounterNonZero" + i
										+ bestfound + ".xls", stringarray[1]);
								writeExcel.write("bestWordCounterAll" + i
										+ bestfound + ".xls", stringarray[2]);
								bestWrongs = totalWrongs;
							} else
								failUpdates++;
						}

						/*
						 * System.out.println("####BEST####"); wordCountersk[0]=
						 * ReadExcel
						 * .readCounters("bestWordCounterZero"+i+bestfound
						 * +".xls", 0, 1); wordCountersk[1]=
						 * ReadExcel.readCounters
						 * ("bestWordCounterNonZero"+i+bestfound+".xls", 0, 1);
						 * wordCountersk[2]=
						 * ReadExcel.readCounters("bestWordCounterAll"
						 * +i+bestfound+".xls", 0, 1); naiveBayes(setsK,
						 * sentimentChance, wordCountersk);
						 */
						bestWordCounter.put(i, bestfound);

					}
					HashMap<String, Float>[] averageweights = trainDataNeutralNonNeutral
							.calcAverages(bestWordCounter);
					trainDataNeutralNonNeutral.createfiles(averageweights);

					kfold = 10;
					sets = new HashMap<Integer, HashMap<String, String>[]>();
					wordCounters = new HashMap<Integer, HashMap<String, Float>[]>();
					bestWordCounter = new HashMap<Integer, Integer>();
					for (int i = 1; i <= kfold; i++) {
						updatePb(1);
						// create sets: {trainset, validationset}
						HashMap<String, String>[] trainVilisetsK = trainDataPosNeg
								.createSets(tweets, i, kfold);
						sets.put(i, trainVilisetsK);
						// create counts: {Positief, Negatief, all}
						HashMap<String, Float>[] wordCountsK = trainDataPosNeg
								.createWordCounts(trainVilisetsK[0]);
						wordCounters.put(i, wordCountsK);
					}
					for (int i = 1; i <= kfold; i++) {
						updatePb(2);
						// {testset, validationset}
						HashMap<String, String>[] setsK = sets.get(i);
						// {Positief, Negatief, all}
						HashMap<String, Float>[] wordCountersk = wordCounters
								.get(i);
						// {Positief, Negatief}
						float[] sentimentChance = trainDataPosNeg
								.getSentimentChance(setsK[0]);
						// classified: {Positief, Negatief, validationPositief,
						// validationNegatief};
						HashMap<String, String[]>[] classifications = trainDataPosNeg
								.naiveBayes(setsK, sentimentChance,
										wordCountersk);

						HashMap<String, String>[] wrongsTrain = trainDataPosNeg
								.getWrongs(classifications[0],
										classifications[1]);
						HashMap<String, String>[] wrongsValidation = trainDataPosNeg
								.getWrongs(classifications[2],
										classifications[3]);

						int bestWrongs = wrongsValidation[0].size()
								+ wrongsValidation[1].size();

						int failUpdates = 0;
						int bestfound = 0;
						HashMap<String, String>[] stringarray = trainDataPosNeg
								.floattostringarray(wordCountersk);

						writeExcel.write("bestWordCounterPositief" + i
								+ bestfound + ".xls", stringarray[0]);
						writeExcel.write("bestWordCounterNegatief" + i
								+ bestfound + ".xls", stringarray[1]);
						writeExcel.write("bestWordCounterAll" + i + bestfound
								+ ".xls", stringarray[2]);

						while (failUpdates < 3) {
							wordCountersk = trainDataPosNeg.updateCounters(
									wrongsTrain, wordCountersk);
							classifications = trainDataPosNeg.naiveBayes(setsK,
									sentimentChance, wordCountersk);
							wrongsTrain = trainDataPosNeg.getWrongs(
									classifications[0], classifications[1]);
							wrongsValidation = trainDataPosNeg.getWrongs(
									classifications[2], classifications[3]);

							int totalWrongs = wrongsValidation[0].size()
									+ wrongsValidation[1].size();
							if (totalWrongs < bestWrongs) {
								bestfound++;
								stringarray = trainDataPosNeg
										.floattostringarray(wordCountersk);
								writeExcel.write("bestWordCounterPositief" + i
										+ bestfound + ".xls", stringarray[0]);
								writeExcel.write("bestWordCounterNegatief" + i
										+ bestfound + ".xls", stringarray[1]);
								writeExcel.write("bestWordCounterAll" + i
										+ bestfound + ".xls", stringarray[2]);
								bestWrongs = totalWrongs;
							} else
								failUpdates++;
						}
						/*
						 * System.out.println("####BEST####"); wordCountersk[0]=
						 * ReadExcel
						 * .readCounters("bestWordCounterPositief"+i+bestfound
						 * +".xls", 0, 1); wordCountersk[1]=
						 * ReadExcel.readCounters
						 * ("bestWordCounterNegatief"+i+bestfound+".xls", 0, 1);
						 * wordCountersk[2]=
						 * ReadExcel.readCounters("bestWordCounterAll"
						 * +i+bestfound+".xls", 0, 1); naiveBayes(setsK,
						 * sentimentChance, wordCountersk);
						 */
						bestWordCounter.put(i, bestfound);

					}
					averageweights = trainDataPosNeg
							.calcAverages(bestWordCounter);
					trainDataPosNeg.createfiles(averageweights);
				} catch (IOException | WriteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (i2 >= howMuch) {
					System.out.println("stopped");
					Toolkit.getDefaultToolkit().beep();
					timer.stop();
					button.setEnabled(true);
					pb.setValue(0);
					String str = "<html>" + "<font color=\"#FF0000\">" + "<b>"
							+ "Klaar met trainen." + "</b>" + "</font>"
							+ "</html>";
					label.setText(str);
					button.setVisible(false);
					backButton.setVisible(true);
					
					
				}

			}
		});
	}

	class ButtonListener implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			System.out.println(ae.getActionCommand());
			if(ae.getActionCommand()=="Start"){
			button.setEnabled(false);
			i2 = 0;
			String str = "<html>" + "<font color=\"#008000\">" + "<b>"
					+ "Training......." + "</b>" + "</font>" + "</html>";
			label.setText(str);
			timer.start();
			}else if(ae.getActionCommand()=="Terug"){
				closeFrame(frame);
				try {
					Jframe.main(null);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void train(final HashMap<Integer, String[]> tweet) {
		new trainStuff(tweet);

	}

	public static void updatePb(int x) {
		i2 += x;

		pb.setValue(i2);
		pb.update(pb.getGraphics());

	}
	
	public static void closeFrame(JFrame frame) {
		frame.dispose();
		frame.setVisible(false);
	}

}